package org.zjt.agent.bytebuddy.threadpool;

import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.matcher.ElementMatchers;
import net.bytebuddy.utility.JavaModule;
import org.zjt.agent.bytebuddy.Interceptor;

import java.lang.instrument.Instrumentation;

import static net.bytebuddy.matcher.ElementMatchers.*;

/**
 * @author juntao.zhang
 * @version V1.0
 * @Description: 失败的案例，agent不能拦截jdk代码
 * @Package org.zjt.agent.bytebuddy.threadpool
 * @date 2017/12/28 22:25
 * com.alibaba.ttl.threadpool.agent.TtlAgent
 */
public class ThreadPoolAgent {

    public static void premain(String arguments, Instrumentation instrumentation) {
        new AgentBuilder.Default()
                .type(ElementMatchers.named("java.util.concurrent.ThreadPoolExecutor"))
                .transform((builder,typeDescription,classLoader,module) -> builder.method(ElementMatchers.nameContainsIgnoreCase("execute")).intercept(MethodDelegation.to(Interceptor.class))
                ).with(new AgentBuilder.Listener(){

                    @Override
                    public void onDiscovery(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded) {

                    }

                    @Override
                    public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded, DynamicType dynamicType) {

                    }

                    @Override
                    public void onIgnored(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded) {

                    }

                    @Override
                    public void onError(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded, Throwable throwable) {
                        throwable.printStackTrace();
                    }

                    @Override
                    public void onComplete(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded) {

                    }
                }).installOn(instrumentation);
    }
}
